package com.example.myapplicationndk.weight;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.myapplicationndk.R;

import java.util.ArrayList;
import java.util.List;

public class NineGridLayout extends ViewGroup {

    /**
     * Context 上下文
     */
    private Context mContext;

    //行
    private int rowCount;       //行

    //列
    private int columnCount;     //列

    public int getImageSpacing() {
        return imageSpacing;
    }

    public void setImageSpacing(int imageSpacing) {
        this.imageSpacing = imageSpacing;
    }

    //图片之间的间隔
    private int imageSpacing = 10;          //px


    public int getmRadius() {
        return mRadius;
    }

    public void setmRadius(int mRadius) {
        this.mRadius = mRadius;
    }

    private int mRadius;

    /**
     * 图片大小
     */
    private int imageWidth;
    private int imageHeight;

    /**
     * 当只有一张图片时的长和宽
     */
    private static final int singleWidth = 430;
    private static final int singleHeight = 560;


    /**
     * 图片的Url集合
     */
    private List<String> mImageUrls = new ArrayList<>();
    /**
     * RoundImageView 的集合
     */
    private List<RoundImageView> mImageViews = new ArrayList<>();


    public NineGridLayout(Context context) {
        super(context);
        mContext = context;
    }

    public NineGridLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    public NineGridLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = 0;
        int totalWidth = width - getPaddingStart() - getPaddingEnd();

        if (mImageUrls.size() > 0) {
            if (mImageUrls.size() == 1) {       //当只有一张图片时的显示大小
                imageWidth = singleWidth;
                imageHeight = singleHeight;
            } else {
                imageWidth = imageHeight = (totalWidth - imageSpacing * 2) / 3;
            }
            width = imageWidth * columnCount + imageSpacing * (columnCount - 1) + getPaddingStart() + getPaddingEnd();
            height = imageHeight * rowCount + imageSpacing * (rowCount - 1) + getPaddingTop() + getPaddingBottom();
        }
        setMeasuredDimension(width, height);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (mImageUrls.size() == 0) {
            return;
        }
        int childCount = mImageUrls.size();
        for (int i = 0; i < childCount; i++) {
            View view = getChildAt(i);
            int rowNum = getRowNum(i + 1);
            int columnNum = getColumnNum(i + 1);

            int left = (imageWidth + imageSpacing) * (columnNum - 1) + getPaddingStart();
            int top = (imageHeight + imageSpacing) * (rowNum - 1) + getPaddingTop();
            int right = left + imageWidth;
            int bottom = top + imageHeight;
            view.layout(left, top, right, bottom);
        }
    }

    /**
     * 获取View所在的row
     */
    private int getRowNum(int i) {
        if (i <= columnCount) {
            return 1;
        } else if (i <= columnCount * 2) {
            return 2;
        } else {
            return 3;
        }
    }

    /**
     * 获取View所在column
     */
    private int getColumnNum(int i) {
        if (i <= columnCount) {
            return i;
        } else if (i <= columnCount * 2) {
            return i - columnCount;
        } else {
            return i - columnCount * 2;
        }
    }


    /**
     * 设置图片的imageUrl 集合
     *
     * @param imageUrl 图片的Url 集合
     */
    public void setImagesData(List<String> imageUrl) {
        this.mImageUrls.clear();
        this.mImageUrls.addAll(imageUrl);
        generateChildrenLayout(imageUrl.size());
    }

    /**
     * 根据图片数量设置图片行列数
     *
     * @param length 图片数量
     */
    private void generateChildrenLayout(int length) {
        if (length <= 3) {
            rowCount = 1;
            columnCount = length;
        } else if (length <= 6) {
            rowCount = 2;
            columnCount = 3;
            if (length == 4) {
                columnCount = 2;
            }
        } else {
            rowCount = 3;
            columnCount = 3;
        }
    }

    /**
     * 刷新控件
     */
    public void notifyDataSetChanged() {
        if (mImageUrls.size() == 0) {
            setVisibility(View.GONE);
            return;
        } else {
            setVisibility(View.VISIBLE);
        }
        removeAllViews();
        int imageCount = mImageUrls.size();
        for (int i = 0; i < imageCount; i++) {
            RoundImageView imageView = getImageView(i);
            imageView.setmRadius(this.getmRadius());
            addView(imageView);
        }
    }

    /**
     * 这里获得ImageView
     * 如果mImageViews 里面的对应位置已经有了ImageView, 此时取出复用
     * 没有的话则创建一个,  保证了对ImageView 的复用
     *
     * @param position 创建ImageView
     * @return RoundImageView
     */
    private RoundImageView getImageView(final int position) {
        RoundImageView imageView;
        if (position < mImageViews.size()) {
            imageView = mImageViews.get(position);
        } else {
            imageView = createImageView();
            imageView.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onImageItemClick(mContext, NineGridLayout.this, position, mImageUrls);
                }
            });
            mImageViews.add(imageView);
        }
        if (mImageLoader != null) {
            mImageLoader.onDisplayImage(mContext, imageView, mImageUrls.get(position));
        }
        return imageView;
    }

    private RoundImageView createImageView() {
        RoundImageView imageView = new RoundImageView(mContext);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setImageResource(R.mipmap.grid_camera);
        return imageView;
    }


    private static ImageLoader mImageLoader;

    public static void setImageLoader(ImageLoader imageLoader) {
        mImageLoader = imageLoader;
    }

    public interface ImageLoader {
        void onDisplayImage(Context context, ImageView imageView, String url);
    }

    public static ImageLoader getImageLoader() {
        return mImageLoader;
    }


    private OnImageItemClickListener listener;

    public void setOnImageItemClickListener(OnImageItemClickListener listener) {
        this.listener = listener;
    }

    public interface OnImageItemClickListener {
        void onImageItemClick(Context context, NineGridLayout layout, int position, List<String> urls);
    }
}
